package com.newbee.sound;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.media.AudioRecord;
import android.os.Environment;
import android.util.Log;

public class SoundRecorder extends Sound
{

	// 音频大小
	private int minBufSize;

	private boolean isRecording = false;

	private Double volume = new Double(0);

	/**********************************************/

	// public static final String DIR = "/udisk/";

	public SoundRecorder()
	{
		minBufSize = AudioRecord.getMinBufferSize(sampleRateInHz,
				channelConfig, audioFormat);

		mRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig,
				audioFormat, minBufSize);
	}

	public void start(final String name)
	{
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
		{
			return;
		}
		this.volume = 0d;
		new Thread(new Runnable()
		{

			@Override
			public void run()
			{
				// TODO Auto-generated method stub
				mRecord.startRecording();

				// new一个byte数组用来存一些字节数据，大小为缓冲区大小
				byte[] audiodata = new byte[minBufSize];
				FileOutputStream fos = null;
				int readsize = 0;
				try
				{
					File file = new File(DIR + name);
					if (file.exists())
					{
						file.delete();
					}
					fos = new FileOutputStream(file);// 建立一个可存取字节的文件
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				isRecording = true;
				while (isRecording == true)
				{
					readsize = mRecord.read(audiodata, 0, minBufSize);

					if (AudioRecord.ERROR_INVALID_OPERATION != readsize)
					{
						try
						{

							calVolume(readsize, audiodata);

							fos.write(audiodata);
						}
						catch (IOException e)
						{
							e.printStackTrace();
						}
					}
				}
				try
				{
					fos.flush();
					fos.close();// 关闭写入流
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}).start();

	}

	public void stop()
	{
		if (mRecord != null)
		{
			isRecording = false;
			mRecord.stop();

		}
	}

	public double getAmplitude()
	{
		synchronized (volume)
		{
			Log.d("getv", "volume------------" + volume);
			return volume;
		}
	}

	public void calVolume(int readSize, byte[] buffer)
	{
		long v = 0;
		// 将 buffer 内容取出，进行平方和运算
		for (int i = 0; i < buffer.length; i++)
		{
			v += buffer[i] * buffer[i];
		}
		// 平方和除以数据总长度，得到音量大小。
		double mean = v / (double) readSize;

		synchronized (volume)
		{
			volume = 10 * Math.log10(mean);
		}

	}

}
